package com.example.demo.http.controllers.user;

import cn.hutool.core.date.DateUtil;
import com.example.demo.models.Activity;
import com.example.demo.models.ActivityUser;
import com.example.demo.models.user.User;
import com.example.demo.services.system.ResultService;
import com.example.demo.services.system.UserService;
import gaarason.database.appointment.Paginate;
import gaarason.database.contract.eloquent.Builder;
import gaarason.database.contract.eloquent.Record;
import gaarason.database.exception.EntityNotFoundException;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/user/activity/")
public class UserActivityController {
    @Resource
    Activity.Model activityModel;
    @Resource
    ActivityUser.Model activityUserModel;

    //查询所有活动
    @GetMapping("/")
    ResultService.Result index(@RequestParam Map<String, String> params) {
        //分页单独处理
        String page = params.get("page");
        if (Objects.isNull(page)) {
            //如果没有页数，默认为第一页
            page = "1";
        }
        //生成查询器
        //查询限制只查询开放的活动
        Builder<Activity, Long> builder = activityModel.newQuery().where(Activity::getIsOpen, "1");
        //放入参数
        params.forEach((key, value) -> {
            if (!Objects.isNull(key) && !key.equals("page")) {
                //要去掉page这个参数，如果还要去掉其他就直接在这里加
                if (!Objects.isNull(value)) {
                    builder.where(key, value);
                }
            }
        });

        //返回结果
        Paginate<Activity> paginate = builder.paginate(page, 15);
        //对结果进行处理
        Map<String, Object> data = new HashMap<>();
        data.put("currentPage", paginate.getCurrentPage());
        data.put("lastPage", paginate.getLastPage());
        data.put("total", paginate.getTotal());
        data.put("perPage", paginate.getPerPage());
        data.put("data", paginate.getItemList());
        ResultService.Result result = ResultService.getNormalResult();
        result.data = data;
        return result;
    }

    //查询单个活动
    @GetMapping("/item")
    ResultService.Result item(@RequestParam Map<String, String> params) {
        //返回值
        ResultService.Result result = ResultService.getNormalResult();
        Record<Activity, Long> activity;
        if (Objects.isNull(params.get("id"))) {
            //活动不存在
            result.code = ResultService.NOT_FOUND;
            result.msg = "活动不存在";
            return result;
        } else {
            try {
                activity = activityModel.newQuery().findOrFail(params.get("id"));
            } catch (EntityNotFoundException e) {
                //找不到活动
                result.code = ResultService.NOT_FOUND;
                result.msg = "活动不存在";
                return result;
            }
            //当前用户
            User user = UserService.getThreadInstance().getUser();
            if (activity.getEntity().getIsOpen().equals(1)) {
                //如果活动开放了
            } else if (activity.getEntity().getNumber().equals(user.getNumber())) {
                //或者创建者就是当前的管理员，那么可以正常执行
            } else {
                //否则假装找不到活动
                result.code = ResultService.NOT_FOUND;
                result.msg = "活动不存在";
                return result;
            }
            //正常返回结果
            result.data = activity.getEntity();
        }
        return result;
    }

    //报名活动
    @PostMapping("/enroll")
    ResultService.Result enroll(@RequestParam Map<String, String> params) {
        //返回值
        ResultService.Result result = ResultService.getNormalResult();
        Record<Activity, Long> activity;
        if (Objects.isNull(params.get("id"))) {
            //活动不存在
            result.code = ResultService.NOT_FOUND;
            result.msg = "活动不存在";
            return result;
        } else {
            try {
                activity = activityModel.newQuery().where(Activity::getIsOpen, "1").findOrFail(params.get("id"));
            } catch (EntityNotFoundException e) {
                //找不到活动
                result.code = ResultService.NOT_FOUND;
                result.msg = "活动不存在";
                return result;
            }
            //当前时间
            Date now = DateUtil.date();
            //如果开始时间不是null，则判断是否早于开始时间
            if (activity.getEntity().getEnrollStart() != null) {
                //活动报名开始时间
                Date start = DateUtil.parse(activity.getEntity().getEnrollStart());
                if (start.after(now)) {
                    //如果“开始”比”现在“大，则说明未到开始时间
                    result.code = ResultService.CLIENT_ERROR;
                    result.msg = "活动报名还未开始";
                    return result;
                }
            }
            //如果结束时间不是null，则判断是否晚于结束时间
            if (activity.getEntity().getEnrollEnd() != null) {
                //活动报名开始时间
                Date end = DateUtil.parse(activity.getEntity().getEnrollEnd());
                if (end.before(now)) {
                    //如果“结束”比”现在“小，则说明未到开始时间
                    result.code = ResultService.CLIENT_ERROR;
                    result.msg = "活动报名已经结束";
                    return result;
                }
            }
            User user = UserService.getThreadInstance().getUser();
            //在时间范围，尝试查找是否已经操作过
            Record<ActivityUser, Long> userRecord = activityUserModel.newQuery().where(ActivityUser::getActivityId, activity.getEntity().getId()).where(ActivityUser::getUserId, user.getId()).first();
            if (userRecord != null) {
                result.code = ResultService.CLIENT_ERROR;
                result.msg = "你已经报名过了";
                return result;
            } else {
                //创建记录
                userRecord = activityUserModel.newRecord();
                userRecord.getEntity().setActivityId(String.valueOf(activity.getEntity().getId()));
                userRecord.getEntity().setActivityId(String.valueOf(user.getId()));
                userRecord.getEntity().setStatus(0);
                result.msg = "报名成功";
            }
        }
        return result;
    }

    //签到活动
    @PostMapping("/sign")
    ResultService.Result sign(@RequestParam Map<String, String> params) {
        //返回值
        ResultService.Result result = ResultService.getNormalResult();
        Record<Activity, Long> activity;
        if (Objects.isNull(params.get("id"))) {
            //活动不存在
            result.code = ResultService.NOT_FOUND;
            result.msg = "活动不存在";
            return result;
        } else {
            try {
                activity = activityModel.newQuery().where(Activity::getIsOpen, "1").findOrFail(params.get("id"));
            } catch (EntityNotFoundException e) {
                //找不到活动
                result.code = ResultService.NOT_FOUND;
                result.msg = "活动不存在";
                return result;
            }
            //当前时间
            Date now = DateUtil.date();
            //如果开始时间不是null，则判断是否早于开始时间
            if (activity.getEntity().getEnrollStart() != null) {
                //活动报名开始时间
                Date start = DateUtil.parse(activity.getEntity().getActivityStart());
                if (start.after(now)) {
                    //如果“开始”比”现在“大，则说明未到开始时间
                    result.code = ResultService.CLIENT_ERROR;
                    result.msg = "活动签到还未开始";
                    return result;
                }
            }
            //如果结束时间不是null，则判断是否晚于结束时间
            if (activity.getEntity().getEnrollEnd() != null) {
                //活动报名开始时间
                Date end = DateUtil.parse(activity.getEntity().getActivityEnd());
                if (end.before(now)) {
                    //如果“结束”比”现在“小，则说明未到开始时间
                    result.code = ResultService.CLIENT_ERROR;
                    result.msg = "活动签到已经结束";
                    return result;
                }
            }
            User user = UserService.getThreadInstance().getUser();
            //在时间范围，尝试查找是否已经操作过
            Record<ActivityUser, Long> userRecord = activityUserModel.newQuery().where(ActivityUser::getActivityId, activity.getEntity().getId()).where(ActivityUser::getUserId, user.getId()).first();
            if (userRecord != null) {
                //如果有记录则配置为“报名后直接签到”
                userRecord.getEntity().setStatus(1);
//                result.code = ResultService.CLIENT_ERROR;
//                result.msg = "你已经报名过了";
//                return result;
            } else {
                //没有记录则配置为“没有报名直接签到”
                userRecord = activityUserModel.newRecord();
                userRecord.getEntity().setActivityId(String.valueOf(activity.getEntity().getId()));
                userRecord.getEntity().setActivityId(String.valueOf(user.getId()));
                userRecord.getEntity().setStatus(2);
//                result.msg = "报名成功";
            }
            result.msg = "签到成功";
        }
        return result;
    }
}
